package com.papercutting.platform.config;

import com.papercutting.platform.entity.User;
import com.papercutting.platform.mapper.UserMapper;
import com.papercutting.platform.util.PasswordUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 数据初始化配置类
 * 在系统启动时初始化默认数据
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {
    
    private final UserMapper userMapper;
    
    @Override
    public void run(String... args) throws Exception {
        initDefaultUser();
    }
    
    /**
     * 初始化默认管理员用户
     */
    private void initDefaultUser() {
        try {
            // 检查是否已存在管理员用户
            User adminUser = userMapper.selectByNickname("admin");
            if (adminUser == null) {
                // 创建默认管理员用户
                adminUser = new User();
                adminUser.setNickname("admin");
                adminUser.setPassword(PasswordUtil.encode("admin")); // 使用BCrypt加密
                adminUser.setUserType(1); // 管理员
                adminUser.setStatus(0); // 正常状态
                adminUser.setCreateTime(LocalDateTime.now());
                adminUser.setUpdateTime(LocalDateTime.now());
                adminUser.setLastLoginTime(LocalDateTime.now());
                adminUser.setDeleted(false);
                adminUser.setPoints(1000);
                
                userMapper.insert(adminUser);
                log.info("默认管理员用户已创建，用户名: admin, 密码: admin");
            } else {
                // 检查密码是否需要重新加密
                String currentPassword = adminUser.getPassword();
                if (currentPassword != null && !currentPassword.startsWith("$2a$")) {
                    // 如果不是BCrypt格式，重新加密
                    adminUser.setPassword(PasswordUtil.encode("admin"));
                    adminUser.setUpdateTime(LocalDateTime.now());
                    userMapper.updateById(adminUser);
                    log.info("管理员用户密码已重新加密");
                }
            }
        } catch (Exception e) {
            log.error("初始化默认用户失败", e);
        }
    }
}